package com.nwcl.common.handler;

import com.nwcl.common.exception.CustomException;
import com.nwcl.common.result.Result;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/*
 * @Description: 统一异常处理
 * @Author liguiqin
 * @Date 2023/5/24 14:20
 * @param: null
 * @return
 * @UpdateDate 2023/5/24 14:20
 **/
@ControllerAdvice
public class GlobalExceptionHandler {
    private Logger log = LogManager.getLogger(GlobalExceptionHandler.class);

    //自定义异常处理
    @ExceptionHandler(CustomException.class)
    public ResponseEntity<Result> handleCustomException(Exception ex) {
        Result errorResponse = Result.fail(ex.getMessage());
        return new ResponseEntity<>(errorResponse, HttpStatus.OK);
    }
    //系统异常处理
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Result> handleException(Exception ex) {
        String msg="服务暂不可用";
        HttpStatus status=HttpStatus.INTERNAL_SERVER_ERROR;
        if(ex instanceof HttpRequestMethodNotSupportedException){
            msg="请求方式不支持";
            status= HttpStatus.METHOD_NOT_ALLOWED;
        }
        Result errorResponse = Result.fail(msg);
        log.error("系统出现异常:", ex);
        return new ResponseEntity<>(errorResponse, status);
    }


}
